import axios from "axios";

//全局配置
//更改axios默认路径，改为 /api 原因是要在vue.config.js里面配置
axios.defaults.baseURL = "/dev-api";
axios.defaults.timeout = 5000;
axios.defaults.headers.post["Content-Type"] = "application/json";
//拦截器
axios.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.error(error);
  }
);
axios.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    return Promise.error(error);
  }
);

export function request(url = "", params = {}, type = "POST") {
  //设置 url params type 的默认值
  return new Promise((resolve, reject) => {
    let promise;
    if (type.toUpperCase() === "GET") {
      promise = axios({
        url,
        params,
      });
    } else if (type.toUpperCase() === "POST") {
      promise = axios({
        method: "post",
        url,
        data: params,
      });
    }
    //处理返回
    promise
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
